<?php
class SQLQuery {
	protected $_dbConnection;
	protected $_result;
	
	/** Database Connection **/
	function connect($address, $account, $pwd, $name) {
		$this->_dbConnection = @mysql_connect($address, $account, $pwd);
		if($this->_dbConnection != 0) {
			return(mysql_select_db($name, $this->_dbConnection));
		} else {
			return FALSE;
		}
	}
	
	/** Database Disconnection **/
	function disconnect() {
		return(@mysql_close($this->_dbConnection));
	}
	
	/** Escape for security purposes **/
	
	function escape($s) {
		return mysql_escape_string($s);
	}
	
	/** Select All **/
	function selectAll() {
		$query = 'SELECT * FROM `' . $this->_table . '`';
		return $this->query($query);
	}
	
	/** Select **/
	function select($id) {
		$query = 'SELECT * FROM `' . $this->_table . '` WHERE `id` = ' . $this->escape($id);
		return $this->query($query, 1);
	}
	
	/** SQL Query **/
	function query($query, $singleResult = FALSE) {
		$this->_result = mysql_query($query, $this->_dbConnection);
		if(preg_match("/select/i", $query)) {
			$result = array();
			$table = array();
			$field = array();
			$tempResults = array();
			$numOfFields = mysql_num_fields($this->_result);
			for($i = 0; $i < $numOfFields; $i++) {
				array_push($table, mysql_field_table($this->_result, $i));
				array_push($field, mysql_field_name($this->_result, $i));
			}
			while($row = mysql_fetch_row($this->_result)) {
				for($i = 0; $i < $numOfFields; $i++) {
					$table[$i] = trim(ucfirst($table[$i]), "s");
					$tempResults[$table[$i]][$field[$i]] = $row[$i];
				}
				if($singleResult) {
					mysql_free_result($this->_result);
					return $tempResults;
				}
				array_push($result, $tempResults);
			}
			mysql_free_result($this->_result);
			return($result);
		}
	}
	
	/** Number of rows **/
	function numRows() {
		return mysql_num_rows($this->_results);
	}
	
	/** Free results **/
	function freeResult() {
		mysql_free_result($this->_result);
	}
	
	function error() {
		return mysql_error($this->_dbConnection);
	}
}







